package miao.byusi.termux.gui;

import miao.byusi.termux.gui.utils.ShellUtils;
import miao.byusi.termux.gui.utils.VncUtils;
import org.apache.commons.cli.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * Termux VNC 服务器主类
 */
public class TermuxVncServer {
    private static final Logger logger = LoggerFactory.getLogger(TermuxVncServer.class);
    private static final int DEFAULT_VNC_PORT = 5900;
    private static final String DEFAULT_PASSWORD = "termux";
    private static final int DEFAULT_WIDTH = 1024;
    private static final int DEFAULT_HEIGHT = 768;
    private static final int DEFAULT_DPI = 96;

    public static void main(String[] args) {
        Options options = createCommandLineOptions();
        CommandLineParser parser = new DefaultParser();

        try {
            CommandLine cmd = parser.parse(options, args);
            
            // 显示帮助信息
            if (cmd.hasOption("help")) {
                printHelp(options);
                return;
            }

            // 解析命令行参数
            int port = getIntOption(cmd, "port", DEFAULT_VNC_PORT);
            String password = cmd.getOptionValue("password", DEFAULT_PASSWORD);
            int width = getIntOption(cmd, "width", DEFAULT_WIDTH);
            int height = getIntOption(cmd, "height", DEFAULT_HEIGHT);
            int dpi = getIntOption(cmd, "dpi", DEFAULT_DPI);
            String shellCommand = cmd.getOptionValue("shell");

            // 环境验证
            validateEnvironment();

            // 安装必要软件包
            VncUtils.installTermuxPackages();
            // 设置显示环境
            VncUtils.setupDisplay(width, height, dpi);
            // 启动VNC服务器
            VncUtils.startVncServer(port, password);

            logger.info("VNC 服务器已启动，端口: {}，分辨率: {}x{}，DPI: {}", 
                    port, width, height, dpi);

            // 执行用户命令（如果有）
            executeUserCommand(shellCommand);

            // 打印连接信息
            printConnectionInfo(port, password);
            // 保持进程运行
            keepProcessAlive();

        } catch (ParseException e) {
            logger.error("命令行参数解析失败", e);
            printHelp(options);
            System.exit(1);
        } catch (Exception e) {
            logger.error("Termux VNC 服务器运行错误", e);
            System.exit(1);
        }
    }

    // 创建命令行选项
    private static Options createCommandLineOptions() {
        Options options = new Options();
        options.addOption("s", "shell", true, "在GUI环境中执行的命令");
        options.addOption("p", "port", true, "VNC服务器端口（默认: " + DEFAULT_VNC_PORT + "）");
        options.addOption("w", "width", true, "屏幕宽度（默认: " + DEFAULT_WIDTH + "）");
        options.addOption("h", "height", true, "屏幕高度（默认: " + DEFAULT_HEIGHT + "）");
        options.addOption("d", "dpi", true, "屏幕DPI（默认: " + DEFAULT_DPI + "）");
        options.addOption("pass", "password", true, "VNC密码（默认: " + DEFAULT_PASSWORD + "）");
        options.addOption("help", "显示帮助信息");
        return options;
    }

    // 获取整数类型选项值
    private static int getIntOption(CommandLine cmd, String opt, int defaultValue) {
        String value = cmd.getOptionValue(opt);
        if (value == null || value.isEmpty()) {
            return defaultValue;
        }
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            logger.warn("参数 {} 的值无效: {}，使用默认值: {}", opt, value, defaultValue);
            return defaultValue;
        }
    }

    // 验证运行环境
    private static void validateEnvironment() throws IOException {
        if (!ShellUtils.isTermuxEnvironment()) {
            throw new IllegalStateException("本程序必须在 Termux 环境中运行");
        }
    }

    // 执行用户命令
    private static void executeUserCommand(String command) throws IOException {
        if (command != null && !command.isEmpty()) {
            logger.info("正在执行用户命令: {}", command);
            String result = ShellUtils.executeCommand(command);
            logger.info("命令输出: {}", result);
        }
    }

    // 打印连接信息
    private static void printConnectionInfo(int port, String password) {
        System.out.println("\n=== Termux GUI VNC 服务器 ===");
        System.out.println("VNC 服务器已成功启动！");
        System.out.println("使用VNC客户端连接：");
        System.out.println("  地址: localhost:" + port);
        System.out.println("  密码: " + password);
        System.out.println("\n按 Ctrl+C 停止服务器...");
    }

    // 保持进程运行
    private static void keepProcessAlive() {
        try {
            while (true) {
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            logger.info("服务器关闭请求");
        }
    }

    // 显示帮助信息
    private static void printHelp(Options options) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar termux-gui-vnc.jar", options);
    }
}